/**
 * ...
 * @author Thot
 */

function Printer()
{
	tomahawk_ns.EventDispatcher.apply(this);
	this.reset();
}


Tomahawk.registerClass(Printer,"Printer");
Tomahawk.extend("Printer","EventDispatcher");

Printer.prototype.LEFT = -1;
Printer.prototype.RIGHT = 1;
Printer.prototype.TOP = -2;
Printer.prototype.BOTTOM = 2;

Printer.prototype._jobs = null;
Printer.prototype._data = null;
Printer.prototype._canvas = null;
Printer.prototype._reverse = false;
Printer.prototype._numFiles = 0;
Printer.prototype.uiPath = null;
Printer.prototype.ficheId = null;
Printer.prototype.width = null;
Printer.prototype.height = null;
Printer.prototype.assetsPath = null;
Printer.prototype._export = null;
Printer.prototype._uiTextures = [
	{url:'picker.png',name:'picker'},
	{url:'cross.png',name:'cross'},
	{url:'resize.png',name:'resize'},
	{url:'rotation.png',name:'rotation'},
	{url:'up.png',name:'up'},
	{url:'DPE_0.png',name:'dpe'},
	{url:'GES_0.png',name:'ges'},
];

Printer.MAX_SIZE = 8192;

Printer.prototype.reset = function()
{
	this._canvas = document.createElement("canvas");
	this._export = new Array();
	this._jobs = new Array();
	this._numFiles = 0;
};

Printer.prototype._loadAssets = function()
{
	var usedTextures = this._getUsedTextures();
	var loader = tomahawk_ns.AssetsLoader.getInstance();
	var i = usedTextures.length;
	
	loader.addEventListener( tomahawk_ns.Event.COMPLETE, this, this._render );
	loader.addEventListener( tomahawk_ns.Event.PROGRESS, this, this._loadProgressHandler );
	
	while( --i > -1 )
	{
		loader.addFile(this.assetsPath + usedTextures[i], usedTextures[i]);
	}
	
	i = this._uiTextures.length;
	
	while( --i > -1 )
	{
		obj = this._uiTextures[i];
		loader.addFile( this.uiPath + obj.url, obj.name );
	}
	
	loader.load();
};

Printer.prototype._getUsedTextures = function()
{
	var data = this._data;
	var dataChild = null;
	var i = 0;
	var max = data.length;
	var results = new Array();

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];

		if( dataChild.type == "TransformableBitmap" && dataChild.textureName != null)
		{
			results.push(dataChild.textureName);
		}
	}
	
	return results;
};

Printer.prototype._loadProgressHandler = function(event)
{
	//var loader = event.target;
	//console.log(loader.getProgression() * 100);
};

Printer.prototype._initCanvas = function()
{
	var canvas = this._canvas;
	var ratio = this.width / this.height;
	
	this.width = ( this.width > Printer.MAX_SIZE ) ? Printer.MAX_SIZE  : this.width;
	this.width = parseInt(this.width);
	this.height = this.width / ratio;
	this.height = parseInt(this.height);
	
	this.height = ( this.height > Printer.MAX_SIZE  ) ? Printer.MAX_SIZE : this.height;
	this.height = parseInt(this.height);
	this.width = this.height * ratio;
	this.width = parseInt(this.width);
	
	// init canvas size
	canvas.width = this.width;
	canvas.height = this.height;
};

Printer.prototype._loadData = function(container)
{
	var data = this._data;
	var dataChild = null;
	var child = null;
	var i = 0;
	var max = data.length;

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];
		
		if( dataChild.type == "TransformableBitmap" )
			child = new TransformableBitmap();
		
		if( dataChild.type == "MesureComponent" )
			child = new MesureComponent();
		
		if( dataChild.type == "TransformableText" )
			child = new TransformableText();
		
		if( child == null )
			continue;
			
		child.unserialize(dataChild);
		container.addChild(child);
	}
};

Printer.prototype._initTextures = function(loader)
{
	var assets = loader.getData();
	var tex = null;
	
	for( var prop in assets )
	{
		tex = new tomahawk_ns.Texture();
		tex.name = prop;
		tex.data = assets[prop];
		tex.rect = [0,0,assets[prop].naturalWidth,assets[prop].naturalHeight];
		tomahawk_ns.AssetsManager.getInstance().addTexture(tex,tex.name);
	}
};

Printer.prototype._render = function(event)
{
	var stage = tomahawk_ns.Stage.getInstance();
	var canvas = this._canvas;
	var context = this._canvas.getContext("2d");
	var isLandscape = ( this.width > this.height );
	var ratio = this.width / this.height;
	var basePortraitWidth = AppConstants.BASE_SIZE;
	var basePortraitHeight = basePortraitWidth / ratio;
	var baseLandscapeHeight = AppConstants.BASE_SIZE;
	var baseLandscapeWidth = baseLandscapeHeight * ratio;
	var baseWidth = (  isLandscape == true ) ? baseLandscapeWidth : basePortraitWidth;
	var loader = event.target;
	var container = new tomahawk_ns.Sprite(); 
	var width = 1;
	var height = 1;
	var image = new Image();
	var scale = this.width / baseWidth;
	this._initTextures(loader);
	this._loadData(container);
	
	loader.removeEventListener( tomahawk_ns.Event.COMPLETE, this, this._render );
	loader.removeEventListener( tomahawk_ns.Event.PROGRESS, this, this._loadProgressHandler );
	
	stage.addChild(container);
	
	for( var i = 0; i < container.children.length; i++ )
	{
		var child = container.getChildAt(i);
		
	
		
		if( child.resize != undefined && child.isText != true )
		{
			width = child.getBody().width;
			height = child.getBody().height;
			child.resize(width * scale, height * scale );
		}
		else
		{
			if( child.isText == true )
			{
				child.refreshTextField();
			}
			child.scaleX = child.scaleY = scale;
		}
		
		child.x *= scale;
		child.y *= scale;
	}
	
	
	context.clearRect(0,0,canvas.width,canvas.height);
	context.setTransform(1,0,0,1,0,0);
	
	context.beginPath();
	context.fillStyle = "white";
	context.fillRect(0,0,canvas.width,canvas.height);
	context.fill();
	
	context.save();
	
	if( this._currentJob.reverse == true )
	{
		container.scaleX = -1;
		container.x += canvas.width;
	}
	
	//stage.draw(canvas.getContext("2d"));
	this.smoothDraw(canvas,canvas.getContext("2d"),stage);
	stage.removeChild(container);
	context.restore();
	
	image.width = canvas.width;
	image.height = canvas.height;
	
	if( this._currentJob.mode == 'jpeg' )
	{
		image.src = canvas.toDataURL('image/jpeg');
	}
	else
	{
		image.src = canvas.toDataURL();
	}
	
	this._currentJob.image = image;
	this._export.push(this._currentJob);
	
	this.dispatchEvent(new tomahawk_ns.Event(tomahawk_ns.Event.PROGRESS, true, true));
	this.print();
};

Printer.prototype.smoothDraw = function(canvas,context,stage)
{
	var off = document.createElement("canvas");
	var off2 = document.createElement("canvas");
	var ctx = off.getContext("2d");
	var ctx2 = off2.getContext("2d");
	var stepX = ( canvas.width >> 2 );
	var stepY = ( canvas.height >> 2 );
	var i = 0;
	var j = 0;
	
	for( i = 0; i < 4; i++ )
	{
		for( j = 0; j < 4; j++ )
		{
			off.width = canvas.width;
			off.height = canvas.height;
			
			off2.width = canvas.width >> 1;
			off2.height = canvas.height >> 1;
			
			ctx.save();
			ctx.scale(4,4);
			ctx.translate(-(stepX*j),-(stepY*i));
			stage.draw(ctx);
			ctx.restore();
			
			ctx2.save();
			ctx2.drawImage(off,0,0,off2.width,off2.height);
			ctx2.restore();
			
			context.save();
			context.translate((stepX*j),(stepY*i));
			context.scale(0.5,0.5);
			context.drawImage(off2, 0, 0 );
			context.restore();
		}
	}
};



Printer.prototype.getExport = function()
{
	return this._export;
};

Printer.prototype.getProgression = function()
{
	var complete = this._numFiles - this._jobs.length;
	var progress = complete / this._numFiles;
	return progress;
};

Printer.prototype.addPrintJob = function(fiche,uiPath,reverse,mode,duo,pos,format)
{
	this._jobs.push({fiche:fiche,format:format,name:fiche.name,uiPath:uiPath,reverse:reverse,mode:mode,pos:pos,duo:duo,image:null});
	this._numFiles++;
};

Printer.prototype.print = function()
{
	if( this._jobs.length == 0 )
	{
		this.resolveDuo();
		this.dispatchEvent(new tomahawk_ns.Event(tomahawk_ns.Event.COMPLETE, true, true));
	}
	else
	{	
		var job = this._jobs.shift();
		var fiche = job.fiche;
		var uiPath = job.uiPath;
		var reverse = job.reverse;
		var size = getFormatSize(job.format);
		var width = size[0];
		var height = size[1];
		
		this._currentJob = job;
		this.uiPath		= uiPath;
		this.ficheId 	= fiche.id;
		this.width 		= (fiche.orientation == fiche.portraitId) ? width : height;
		this.height 	= (fiche.orientation == fiche.portraitId) ? height : width;
		this.assetsPath = fiche.assetsPath;
		this._data 		= fiche.data;
		this._reverse = ( reverse == true );
		this._initCanvas();
		this._loadAssets();
	}
};



Printer.prototype._getJobIndexByFicheId = function(id)
{
	var i = this._export.length;
	
	while( --i > -1 )
	{
		if( this._export[i].fiche.id == id )
		{
			return i;
		}
	}
	
	return -1;
};

Printer.prototype.resolveDuo = function()
{
	var i = this._export.length;
	var current = null;
	var duo = null;
	var newJob = null;
	var index = null;
	var canvas = document.createElement("canvas");
	var context = canvas.getContext("2d");
	var isLandscape = false;
	
	while( --i > -1 )
	{
		current = this._export[i];
		index = this._getJobIndexByFicheId(current.duo);
		
		if( index == -1 )
			continue;
		
		duo = this._export[index];
		this._export.splice(index,1);
		
		isLandscape = ( current.image.width > current.image.height );
		context.save();
		
		if( duo.pos > 0 )
		{
			first = current;
			second = duo;
		}
		else
		{
			first = duo;
			second = current;
		}
		
		if( isLandscape == true )
		{
			canvas.width = first.image.width;
			canvas.height = first.image.height * 2;
			context.drawImage(first.image, 0, 0, first.image.width, first.image.height );
			context.drawImage(second.image, 0, first.image.height, second.image.width, second.image.height );
		}
		else
		{
			canvas.width = first.image.width * 2;
			canvas.height = first.image.height;
			context.drawImage(first.image, 0, 0, first.image.width, first.image.height );
			context.drawImage(second.image, first.image.width, 0, second.image.width, second.image.height );
		}
		
		context.restore();
		
		current.image = new Image();
		current.image.width = canvas.width;
		current.image.height = canvas.height;
		
		if( current.mode == 'jpeg' )
		{
			current.image.src = canvas.toDataURL('image/jpeg');
		}
		else
		{
			current.image.src = canvas.toDataURL();
		}
		
		current.name += "-"+duo.name;
	}
};
//



